import { resolve } from "node:path";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import vueDevTools from "vite-plugin-vue-devtools";
import { configHtmlPlugin } from "./vite/plugins/html";
import { configSvgIconsPlugin } from "./vite/plugins/svg-image";
import AutoImport from "unplugin-auto-import/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";

// https://vitejs.dev/config/
export default defineConfig(({ command }) => {
  const isBuild = command === "build";
  const root = process.cwd();
  const pathResolve = (pathname: string) => resolve(root, ".", pathname);
  const timestamp = new Date().getTime();
  return {
    plugins: [
      vue(),
      vueJsx(),
      // vueDevTools(),
      // vite-plugin-html
      configHtmlPlugin({ isBuild }),
      // vite-plugin-svg-icons
      configSvgIconsPlugin({ isBuild }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
        ],
        resolvers: [ElementPlusResolver()],
      }),
    ],

    resolve: {
      alias: [
        {
          find: /@\//,
          replacement: pathResolve("src") + "/",
        },
        {
          find: /#\//,
          replacement: pathResolve("types") + "/",
        },
        {
          find: /@hooks/,
          replacement: pathResolve("src") + "/hooks",
        },
      ],
      extensions: [".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    server: {
      proxy: {
        "/xydElement": {
          timeout: 30000,
          target: "http://192.168.0.126:12312",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/xydElement/, ""),
        },
      },
    },
    build: {
      target: "es2015",
      cssTarget: "chrome80",
      rollupOptions: {
        output: {
          // 入口文件名
          entryFileNames: `assets/entry/[name]-[hash]-${timestamp}.js`,
          manualChunks: {
            vue: ["vue", "pinia", "vue-router"],
          },
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `
          @use "@/assets/styles/element/index.scss" as *; 
          @use "@/assets/styles/config.scss" as config; `,
          javascriptEnabled: true,
        },
      },
    },
  };
});
